package cn.kent.heima.base.directMemory;

import sun.misc.Unsafe;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * 直接内存释放 只能通过unsafe类释放
 *      回收只能使用unsafe主动释放
 */
public class Demo_12 {
    static int _1Gb = 1024 * 1024 * 1024;

    public static void main(String[] args) throws IOException {
        Unsafe unsafe = getUnsafe();
        long base = unsafe.allocateMemory(_1Gb);
        unsafe.setMemory(base, _1Gb, (byte) 0);
        System.out.println("已分配1Gb内存");
        System.in.read();
        System.out.println("已释放1Gb内存");
        unsafe.freeMemory(base);
        System.in.read();
    }

    public static Unsafe getUnsafe() {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            Unsafe unsafe = (Unsafe) f.get(null);
            return unsafe;
        } catch (IllegalAccessException | NoSuchFieldException exception) {
            throw new RuntimeException(exception);
        }
    }
}
